<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Models\Goods;

class CartRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'goods_id' => 'required|exists:goods,id',
            'quantity' => 'required|integer|min:1',
        ];
    }

    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $validator->sometimes('attrs', 'required', function($input) {
                $goods_id = $input->goods_id;
                $goods = Goods::find($goods_id);
                return $goods && $goods->attrs()->exists();
            });
        });
    }

    public function messages()
    {
        return [
            'attrs.required' => '请选择商品规格',
        ];
    }
}
